<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button v-permission="'add-role'" size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>
              {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="onEdit(row)">确定</el-button>
              <el-button size="mini" type="danger" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button
                v-permission="'assign-role'"
                size="mini"
                type="text"
                @click="btnPermission(row.id)"
              >分配权限</el-button>
              <el-button v-permission="'edit-role'" size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <!-- 气泡弹层 -->
              <el-popconfirm title="这是一段内容确定删除吗？" style="margin-left:8px;" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" v-permission="'del-role'" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

      <!-- 弹层 -->
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
        <!-- 表单内容 -->
        <el-form ref="roleForm" label-width="120px" :model="roleForm" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
                <el-button size="mini" @click="btnCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 分配权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <el-tree
          ref="perTreeRef"
          node-key="id"
          :data="permissionData"
          :props="{ label: 'name' }"
          :default-checked-keys="permIds"
          default-expand-all
          show-checkbox
          check-strictly
        />
        <div style="text-align:center; margin-top:10px;">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionListApi } from '@/api/permission'
import { addRoleApi, assignPermApi, delRoleApi, getRoleDetailApi, getRoleListApi, updateRoleApi } from '@/api/role'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      // ---------------------------
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: '',
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows, total } = await getRoleListApi(this.pageParams)
      this.list = rows // 赋值数据
      this.pageParams.total = total
      // 给数据数组中每一个对象添加一个isEdit属性
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        // 添加一个对象
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRoleApi(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 编辑行内数据
    btnEditRow(row) {
      row.isEdit = true
      // 重新给临时行数据对象赋值
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    // 编辑行内数据
    async onEdit(row) {
      // 1. 数据校验
      if (!row.editRow.name.trim() || !row.editRow.description.trim()) {
        this.$message.warning('角色名称和描述不能为空~')
        return
      }
      // 2. 调用接口
      await updateRoleApi({ id: row.id, ...row.editRow })
      this.$message.success('修改角色成功~')
      // 3. 退出编辑
      // row.isEdit = false
      Object.assign(row, {
        isEdit: false,
        ...row.editRow
      })
    },
    async confirmDel(id) {
      await delRoleApi(id)
      // 最后一页, 最后一条数据
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page -= 1
      }
      this.$message.success('删除角色成功')
      this.getRoleList()
    },
    // 打开分配权限弹窗
    async btnPermission(id) {
      this.currentRoleId = id
      // 1. 获取所有的权限
      this.permissionData = transListToTreeData(await getPermissionListApi(), 0)
      // 2. 获取角色拥有的权限
      const { permIds } = await getRoleDetailApi(id)
      this.permIds = permIds
      this.showPermissionDialog = true
    },
    async btnPermissionOK() {
      // console.log(this.$refs.perTreeRef.getCheckedKeys())
      await assignPermApi({
        id: this.currentRoleId,
        permIds: this.$refs.perTreeRef.getCheckedKeys()
      })
      this.$message.success('权限分配成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
 .app-container{
  padding: 20px;
 }
 .role-operate {
   padding: 10px;
 }
</style>
